<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta http-equiv="Access-Control-Allow-Origin" content="*">
    <title>客户端</title>
</head>

<body style="overflow: hidden;">
<!--这里是HTML内容区-->
<div id="wrapBox">

</div>
<div id="btn" style="position: fixed;bottom: 100px; right: 10px;">
    <button id="stopRequest">停止请求</button>
    <button id="scroll">开启滚动</button>
    <button id="stop">停止滚动</button>
</div>

<script src="jquery.min.js"></script>
<script src="socket.io.js"></script>
<script>
    var socketIoUrlClient    = 'https://ws.mb928.com:4430/client';
    //var webSocketUrlClient   = 'ws://192.168.10.31:17072';
    var deBug   = true;
    var connectType = 'socketIo'; //链接模式：webSocket; socketIo

    var isPing   = false; //是否开启心跳
    var pingTime = 10000; //发送心跳时间 10 秒

    var socket  = null;
    var token   = 0;

    //请求参数
    var param = getRequest();
    var third_party_id = parseInt(param.third_party_id);
    var node_id        = parseInt(param.node_id);

    var room_id = 0;
    var start_msg_id=0;

    var scrollTrue = true;//屏幕是否滚动
    var questNum   = 0;//请求次数

    var setIntervalId = 0;//定时器id

    //页面初始化，加载入口
    window.onload = function() {
        if(!third_party_id || !node_id){
            alert('third_party_id、node_id参数不能为空');
            return ;
        }

        //请求服务
        if(connectType == 'webSocket'){
            connectWebSocket();
        } else {
            connectSocketIo();
        }

        $("#wrapBox").css({"height":$(window).height()-200, "overflow-y":"auto"});
        //滚动
        $(document).on("click", "#scroll", function(){
            scrollTrue = true;
        });
        //停止滚动
        $(document).on("click", "#stop", function(){
            scrollTrue = false;
        });
        //停止请求
        $(document).on("click", "#stopRequest", function(){
            socket = null;
            alert('总共发起'+questNum+'次会话');
        });
    };

    //链接 socketIo
    var connectSocketIo = function () {
        deBugLog('socketIo模式');
        if (socket != null) {
            return ;
        }

        socket = io(socketIoUrlClient);

        //连接成功事件
        socket.on('connect', function () {
            deBugLog('connected 链接成功');
            //发送登陆请求
            var requestParam = '{"cmd": "cmd_client_login_req", "third_party_id": '+third_party_id+', "node_id":'+node_id+' }';
            sendMsgToService(requestParam, '-----发送登陆请求：');

            //十秒发送一次心跳
            if(isPing == true){
                if(setIntervalId > 0){
                    clearInterval(setIntervalId);
                }

                setIntervalId = setInterval(function(){
                    var requestParam = '{"cmd": "cmd_client_ping_req", "third_party_id": '+third_party_id+', "node_id":'+node_id+' }';
                    sendMsgToService(requestParam, '-----发送心跳：');
                }, pingTime);
            }


            return ;
        });

        //收到服务器消息响应事件
        socket.on('server_reply_event', function (obj) {
            handleRsp(obj);

            return ;
        });
    };

    //连接webSocket
    var connectWebSocket = function() {
        deBugLog('webSocket模式');
        if (socket != null) {
            return ;
        }

        if ('WebSocket' in window) {
            socket = new WebSocket(webSocketUrlClient);
        } else if ('MozWebSocket' in window) {
            socket = new MozWebSocket(webSocketUrlClient);
        } else {
            alert('您的浏览器不支持WebSocket')
            return ;
        }

        //链接成功
        socket.onopen = function() {
            deBugLog('connected 链接成功');

            //请求客服
            var requestParam = '{"cmd": "cmd_client_request_service_req", "third_party_id": '+third_party_id+', "node_id":'+node_id+', "question_type":1, "device_type":"h5", "app_version":"h5" }';
            sendMsgToService(requestParam, '-----发送请求客服：');

            //十秒发送一次心跳
            if(isPing == true){
                if(setIntervalId > 0){
                    clearInterval(setIntervalId);
                }

                setIntervalId = setInterval(function(){
                    var requestParam = '{"cmd": "cmd_client_ping_req", "third_party_id": '+third_party_id+', "node_id":'+node_id+' }';
                    sendMsgToService(requestParam, '-----发送心跳：');
                }, pingTime);
            }

            return ;
        };

        //收到消息
        socket.onmessage = function(e) {
            var obj = JSON.parse(e.data);//解析字符串为JSON对象
            handleRsp(obj);

            return ;
        };
    };

    //处理消息响应
    var handleRsp = function (obj) {
        deBugLog('收到消息-----');
        deBugLog(obj);

        if (obj.header.error_code != 0){
            return ;
        }

        //登陆返回
        if (obj.header.cmd == 'cmd_client_login_rsp'){
            token = obj.data.token;

            //请求客服
            var requestParam = '{"cmd": "cmd_client_request_service_req", "third_party_id": '+third_party_id+', "node_id":'+node_id+', "question_type":1, "device_type":1, "app_version":"h5" }';
            sendMsgToService(requestParam, '-----发送请求客服：');

            return ;
        }

        //请求客服返回
        if (obj.header.cmd == 'cmd_client_request_service_rsp'){
            room_id = obj.data.room_id;
            printScreen(third_party_id+' 请求客服，房间号：'+obj.data.room_id+'<br>');

            return ;
        }

        //有新消息通知
        if (obj.header.cmd == 'cmd_client_has_new_msg_push'){
            // 请求拉取新消息
            var requestParam = '{"cmd": "cmd_client_pull_new_msg_req", "third_party_id": '+third_party_id+', "node_id":'+node_id+', "start_msg_id":'+start_msg_id+', "count":10, "direction":1 }';
            sendMsgToService(requestParam, '-----请求拉取新消息：');

            return ;
        }

        //拉取新消息返回
        if (obj.header.cmd == 'cmd_client_pull_new_msg_rsp'){
            start_msg_id = obj.data.msg[obj.data.msg.length - 1].msg_id;

            var tmpArr    = obj.data.msg;
            var tmpLength = obj.data.msg.length;
            for(var i = 0; i < tmpLength; i++) {
                //正在呼叫客服
                if(tmpArr[i].direction == 1 &&
                    tmpArr[i].data[0] &&
                    tmpArr[i].data[0].content_type &&
                    tmpArr[i].data[0].content_type == 'service_waitting'

                ){
                    var msgObj = tmpArr[i].data[0];
                    printScreen(msgObj.text+'<br>');
                    continue;
                }

                //客服接待客户
                if(tmpArr[i].direction == 1 &&
                    tmpArr[i].data[0] &&
                    tmpArr[i].data[0].content_type &&
                    tmpArr[i].data[0].content_type == 'service_receive'

                ){
                    var msgObj = tmpArr[i].data[0];
                    printScreen(msgObj.text+'<br>');

                    var requestParam = '{"cmd": "cmd_client_send_msg_req", "third_party_id": '+third_party_id+', "node_id":'+node_id+', "msg":[{"content_type":"text", "text":"客服你好！"}] }';
                    sendMsgToService(requestParam, '-----您发送消息：');

                    printScreen('发送一条消息：客服你好！<br>');
                    break;
                }

                //收到客服回复，发送结束对话
                if(tmpArr[i].direction == 1 &&
                    tmpArr[i].data[0] &&
                    tmpArr[i].data[0].content_type &&
                    tmpArr[i].data[0].content_type == 'text'

                ){
                    var msgObj = tmpArr[i].data[0];
                    printScreen('收到客服回复：'+msgObj.text+'<br>');

                    var requestParam = '{"cmd": "cmd_client_end_service_req", "third_party_id": '+third_party_id+', "node_id":'+node_id+' }';
                    sendMsgToService(requestParam, '-----您发送结束对话：');

                    break;
                }
            }

            return ;
        }

        //结束客服，返回
        if(obj.header.cmd == 'cmd_client_end_service_rsp'){
            printScreen('您结束了对话。<br><br><br>');

            //删除旧的定时器
            if(setIntervalId > 0){
                clearInterval(setIntervalId);
            }

            //参数重置
            socket  = null;
            token   = 0;
            room_id = 0;
            start_msg_id = 0;
            setIntervalId = 0;

            //重新链接，请求客服
            questNum++;
            third_party_id++;
            if(connectType == 'webSocket'){
                connectWebSocket();
            } else {
                connectSocketIo();
            }

            return ;
        }

    };

    /**
     * 向服务器发消息
     * @param msgStr    发送的json字符串
     * @param deBugStr  deBug提示文字
     */
    var sendMsgToService = function (msgStr, deBugStr) {
        if(socket == null){
            printScreen('链接已经断开<br>');
            deBugLog('链接已经断开');
            return ;
        }

        deBugStr = deBugStr || '请求参数：';

        if(connectType == 'webSocket'){
            //webSocket模式，直接发送json字符串
            deBugLog(deBugStr + msgStr);
            socket.send(msgStr);
        } else {
            //socketIo模式，需要封装带上TOKEN，并将json字符串转为json对象发送
            var req = ' { "token":'+token+', "data":'+msgStr+' } ';
            deBugLog(deBugStr + req);
            socket.emit('client_event', JSON.parse(req));
        }
    };

    /**
     * 打印日志
     */
    var deBugLog = function (msg) {
        if(deBug){
            console.log(msg);
        }
        return ;
    };

    /**
     * 输出结果到屏幕
     * @param text
     */
    var printScreen = function (text) {
        $("#wrapBox").append(text);

        if(scrollTrue == true){
            document.getElementById("wrapBox").scrollTop = document.getElementById("wrapBox").scrollHeight;
        }
    };

    /**
     * 获取URL参数
     * @returns {Object}
     */
    function getRequest () {
        var url = location.search; //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            strs = str.split("&");
            for(var i = 0; i < strs.length; i ++) {
                theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    }

</script>
</body>
</html>